#!/bin/sh

e2e_test_install() {
  kubectl create namespace "$CLUSTER_NAMESPACE"

  deploy_curl_pod "$CLUSTER_NAMESPACE"

  wait_pods_running "$CLUSTER_NAMESPACE" 1
}

e2e_test() {
  run_test "Storage endpoint should be available" check_storage_classes_status

  run_test "Storage endpoint should return all kubernetes storage classes" check_storage_classes

  run_test "User with wrong credentials should not be authenticated" test_authentication_api_error
}

check_storage_classes() {
  local STORAGE_CLASSES_IN_RESPONSE
  local STORAGE_CLASSES_IN_K8

  STORAGE_CLASSES_IN_RESPONSE="$(run_curl -r "stackgres/storageclasses" -n "$CLUSTER_NAMESPACE" | jq 'length')"

  STORAGE_CLASSES_IN_K8S="$(kubectl get storageclasses -o json | jq '.items | length')"

  if [ "$STORAGE_CLASSES_IN_RESPONSE" = "$STORAGE_CLASSES_IN_K8S" ]
  then
    success "Storage classes endpoint returned all storage classes"
  else
    fail_no_return "Storage classes endpoint did not return all storage classes. Expected $STORAGE_CLASSES_IN_K8S, actual $STORAGE_CLASSES_IN_K8S"
  fi
}


get_storage_classes_status() {
  run_curl -r "stackgres/storageclasses" -n "$CLUSTER_NAMESPACE" -e "-LI -o /dev/null -w %{http_code}"
}

check_storage_classes_status() {
  local HTTP_STATUS

  HTTP_STATUS="$(get_storage_classes_status)"

  if [ "$HTTP_STATUS" = "200" ] || [ "$HTTP_STATUS" = "202" ] || [ "$HTTP_STATUS" = "204" ]
  then
    success "Storage classes endpoint is available"
  else
    fail "Storage classes endpoint is not available"
  fi
}

test_authentication_api_error() {
  local HTTP_STATUS

  HTTP_STATUS="$(run_curl -j "$FAKE_JWT" -r "stackgres/storageclasses"  -n "$CLUSTER_NAMESPACE" -e "-LI -o /dev/null -w %{http_code}")"

  check_authentication_error
}

check_authentication_error() {
  if [ "$HTTP_STATUS" = "401" ]
  then
    echo "Request returned expected authentication error"
    return 0
  else
    echo "Request returned unexpected response status $HTTP_STATUS instead of the expected authentication error."
    return 1
  fi
}